package com.gang.ssm.bos.system.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.gang.ssm.bos.common.Page;
import com.gang.ssm.bos.common.TreeNode;
import com.gang.ssm.bos.core.anotation.Permission;
import com.gang.ssm.bos.core.toolbox.ajax.AjaxResult;
import com.gang.ssm.bos.core.toolbox.kit.JsonUtils;
import com.gang.ssm.bos.system.bean.Menu;
import com.gang.ssm.bos.system.bean.Role;
import com.gang.ssm.bos.system.service.MenuService;
import com.gang.ssm.bos.system.service.RoleService;

@Controller
@RequestMapping("/role")
public class RoleController extends BosController {
	
	@Autowired
	private RoleService roleService;
	
	@Autowired
	private MenuService menuService;
	
	@RequestMapping("/list")
	public String list(Page<Role> page, Map<String, Object> map) {
		
		roleService.pageQuery(page);
		map.put("page", page);
		return "system/role/roleList";
	}
	
	@RequestMapping("/role")
	public String input(Integer id, Map<String, Object> map) {
		
		List<Integer> menuIds = null;
		if(id != null) {
			map.put("role", roleService.findById(id));
			
			menuIds = menuService.findMenuIdsByRoleId(id);
		}
		
		List<Menu> menuList = menuService.findAll();
		List<TreeNode> treeNodes = new ArrayList<TreeNode>();
		TreeNode treeNode = null;
		
		for (Menu menu : menuList) {
			treeNode = new TreeNode();
			treeNode.setId(menu.getId());
			treeNode.setName(menu.getMenuName());
			treeNode.setpId(menu.getParentId());
			
			if(!CollectionUtils.isEmpty(menuIds)) {
				if(menuIds.contains(menu.getId())) {
					treeNode.setChecked(true);
				}
			}
			
			treeNodes.add(treeNode);
		}
		map.put("menuList", JsonUtils.objectToJson(treeNodes));
		
		return "system/role/role";
	}
	
	@Permission({ADMIN})
	@ResponseBody
	@RequestMapping("/save")
	public AjaxResult save(Role role, String menuIds) {
		
		try {
			roleService.saveOrUpdate(role, menuIds);
			success("保存成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fail("保存失败!");
	}
	
	@Permission({ADMIN})
	@ResponseBody
	@RequestMapping("/delete")
	public AjaxResult delete(Integer id) {
		
		try {
			roleService.deleteById(id);
			return success("删除成功!");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fail("删除失败!");
	}
	
}
